<?php
namespace app\admins\controller;
use think\Controller;
use Util\data\Sysdb;



class Roles  extends BaseAdmin
{
	public function index(){
		$data['roles']=$this->db->table('admin_groups')->lists();
		$this->assign('data',$data);
		return $this->fetch();

	}

    	// 角色添加
	public function add(){
		$gid = (int)input('get.gid');
		$role = $this->db->table('admin_groups')->where(array('gid'=>$gid))->item();
		$role && $role['rights'] && $role['rights'] = json_decode($role['rights']);
		
		$this->assign('role',$role);

		$menu_list = $this->db->table('admin_menus')->where(array('status'=>0))->cates('mid');
		$menus = $this->gettreeitems($menu_list);
		
		$this->assign('menus',$menus);
		return $this->fetch();
	}

	private function gettreeitems($items){
		$tree = array();
		foreach ($items as $item) {
			if(isset($items[$item['pid']])){
				$items[$item['pid']]['children'][] = &$items[$item['mid']];
			}else{
				$tree[] = &$items[$item['mid']];
			}
		}
		return $tree;
	}


	public function save(){
		$gid=(int)input('post.gid');
		$data['title']=trim(input('post.title'));
		$menus=input('post.menu/a');
		if(!$data['title']){
			json_encode(array('code'=>1,'msg'=>'角色名称不能为空'));
		}
		$menus&&$data['rights']=json_encode(array_keys($menus));
		if($gid>0){
			//编辑修改
			$this->db->table('admin_groups')->where(array('gid'=>$gid))->update($data);

		}else{
			$this->db->table('admin_groups')->insert($data);

		}
		exit(json_encode(array('code'=>0,'msg'=>'保存成功')));
    }


    //删除
    public function delete(){
    	$gid=(int)input('gid');
    	$this->db->table('admin_groups')->where(array('gid'=>$gid))->delete();
    	exit(json_encode(array('code'=>0,'msg'=>'删除成功')));
    }



}